#include <iostream>
#include <string>
#include <memory>
#include <ctime>
#include "Socket.hpp"
#include "Protocol.hpp"
#include "InetAddr.hpp"

using namespace sock_ns;
using namespace protocol_ns;


void Usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << " serverip serverport\n"
              << std::endl;
}



int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    InetAddr serveraddr = InetAddr(serverip,serverport);
    Factory factory;
    std::unique_ptr<Socket> cli = std::make_unique<TcpSocket>();
    bool ret = cli->BuildClientSocket(serveraddr);
    std::string inbuffer;
    while(ret)
    {
        sleep(1);
        auto req = factory.BuildRequest();

        //把序列化后的指令放到send_str中
        std::string send_str;
        req->Serialize(&send_str);

        std::cout << "Serialize: \n"<< send_str << std::endl;

        //添加报头
        send_str = Encode(send_str);
        std::cout << "Encode: \n"<< send_str << std::endl;

        cli->Send(send_str);

        //读取内容
        int n = cli->Recv(&inbuffer);
        if(n<=0)
        {
            break;
        }
        std::string package = Decode(inbuffer);
        if (package.empty())
            continue;

        //保证package一定是一个完整的应答
        auto resp = factory.BuildResponse();

        //反序列化
        resp->DelSerialize(package);


        std::cout << resp->_result << "[" << resp->_code << "]" << std::endl;

    }

    return 0;
}